import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

public class ReportMailer
{

    public ReportMailer()
    {
    }

    public void sendReport(Team t, String title, String subject, Judicator j) throws EmailException
    {
    	//java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    	
        boolean hasPlain = false, hasHtml = false;
        for (Student s : t.students)
        {
            if (s.preferredFormat == Student.HTML) hasHtml = true;
            else if (s.preferredFormat == Student.PLAIN) hasPlain = true;
        }

        if (hasHtml)
        {
            HtmlReportWriter hrw = new HtmlReportWriter();
            String report = hrw.getReport(t, title, j);

            HtmlEmail email = new HtmlEmail();
            email.setHostName(Settings.getSmtp());

            for (Student s : t.students)
            {
                if (s.preferredFormat == Student.HTML)
                    email.addTo(s.email);
            }

            email.setSmtpPort(587);
            email.setAuthenticator(new DefaultAuthenticator(Settings.getLogin(), Settings.getPass()));
            email.setDebug(true);

            /*DEBUG*/ email.addTo(Settings.getLogin());            
            email.setFrom(Settings.getLogin(), Settings.getOperatorName());
            email.setAuthentication(Settings.getLogin(), Settings.getPass());
            email.setSubject(subject);            
            email.setHtmlMsg(report);
            email.setTLS(true);
            email.setAuthentication(Settings.getLogin(), Settings.getPass());
            
            
            email.send();
        }

        if (hasPlain)
        {
            PlainReportWriter prw = new PlainReportWriter();
            String report = prw.getReport(t, title, j);

            SimpleEmail email = new SimpleEmail();
            email.setHostName(Settings.getSmtp());

            for (Student s : t.students)
            {
                if (s.preferredFormat == Student.PLAIN)
                    email.addTo(s.email);
            }

            /*DEBUG*/ email.addTo(Settings.getLogin());
            email.setFrom(Settings.getLogin(), Settings.getOperatorName());
            email.setAuthentication(Settings.getLogin(), Settings.getPass());
            email.setSubject(subject);
            email.setMsg(report);
            email.setTLS(true);
            email.send();
        }
    }
}
